// pages/admin/users/users.js
const app = getApp();

Page({
  data: {
    userList: [],
    total: 0,
    page: 1,
    pageSize: 20,
    role: '',
    search: '',
    roles: [
      { value: '', text: '全部' },
      { value: 'student', text: '学生' },
      { value: 'teacher', text: '教师' },
      { value: 'counselor', text: '辅导员' },
      { value: 'admin', text: '管理员' }
    ],
    loading: false,
    activeTab: 0 // 添加当前激活的标签索引
  },

  onLoad: function() {
    this.fetchUserList();
  },

  // 添加切换标签方法
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    const role = this.data.roles[index].value;
    
    this.setData({
      activeTab: index,
      role: role,
      page: 1
    }, () => {
      this.fetchUserList();
    });
  },

  // 获取用户列表
  fetchUserList: function() {
    this.setData({ loading: true });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/users`,
      method: 'GET',
      data: {
        page: this.data.page,
        pageSize: this.data.pageSize,
        role: this.data.role,
        search: this.data.search
      },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        console.log('获取用户列表成功:', res.data);
        if (res.statusCode === 200) {
          // 添加调试日志
          console.log('设置前的 userList:', this.data.userList);
          
          this.setData({
            userList: res.data.data || [],
            total: res.data.total
          });
          
          // 添加调试日志
          console.log('设置后的 userList:', this.data.userList);
          console.log('userList 长度:', this.data.userList.length);
        } else {
          wx.showToast({
            title: res.data.message || '获取用户列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取用户列表失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 搜索用户
  onSearch: function(e) {
    this.setData({
      search: e.detail.value,
      page: 1
    }, () => {
      this.fetchUserList();
    });
  },

  // 角色筛选
  onRoleChange: function(e) {
    this.setData({
      role: e.detail.value,
      page: 1
    }, () => {
      this.fetchUserList();
    });
  },

  // 分页切换
  onPageChange: function(e) {
    const page = e.detail.current;
    this.setData({ page }, () => {
      this.fetchUserList();
    });
  },

  // 添加用户
  addUser: function() {
    wx.navigateTo({
      url: '/pages/admin/users/add/add'
    });
  },

  // 编辑用户
  editUser: function(e) {
    const userId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/admin/users/edit/edit?id=${userId}`
    });
  },

  // 删除用户
  deleteUser: function(e) {
    const userId = e.currentTarget.dataset.id;
    const userName = e.currentTarget.dataset.name;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除用户 ${userName} 吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.performDelete(userId);
        }
      }
    });
  },

  // 执行删除操作
  performDelete: function(userId) {
    wx.showLoading({ title: '删除中...' });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/users/${userId}`,
      method: 'DELETE',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          // 刷新列表
          this.fetchUserList();
        } else {
          wx.showToast({
            title: res.data.message || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('删除用户失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({ page: 1 }, () => {
      this.fetchUserList();
      wx.stopPullDownRefresh();
    });
  }
})